$(document).ready(function(){
	currentURL = $(location).attr('href');
	jsonRequest = currentURL + 'json.php';
	
	
	javascriptActive();
	setCurrentMenu();
	
	/*
	*	Login Form
	*/
	$('#loginButton').click(function()  {
		deleteErrorMessage();
		var loginData = $('#loginRequest').serializeArray();
		
		loginData.push(getFunctionObject('login'));
		
		$.post(jsonRequest, loginData, function(data)  {
			alert(data);
		});
	});

	/*
	*	Edit Subscriber
	*/

	$("#subscriberButton").click(function(){
		deleteErrorMessage();
		var subscriberData = $("#subscriberRequest").serializeArray();

		subscriberData.push(getFunctionObject('subscriberEdit'));
		
  		$.post("http://admin.k6.de/index.php?id=22", subscriberData, function(data) {
			var jsonString = $("." + data+ ".tx-ttadminpanelservice-pi1").text().trim();
			var obj = jQuery.parseJSON(jsonString);

			if (!obj.error)  {
				$("#subscriberRequest").submit();
			}
			else  {
			var errorMessages = new Array;
			
			$("#subscriberRequestInput").attr("class", "errorInput");
			
			errorMessages[0] = obj.error.msg;
			setErrorMessages(errorMessages);
			makeErrorMessagesVisible();
			}
		});
	});
	
	/*
	*	Password Request Subscribers
	*/
	
	$("#passwordButton").click(function()  {
		var subscriberData = $("#subscriberRequest").serializeArray();

		subscriberData.push(getFunctionObject('subscriberEdit'));
		
  		$.post("http://admin.k6.de/index.php?id=22", subscriberData, function(data) {
			var jsonString = $("." + data + ".tx-ttadminpanelservice-pi1").text().trim();
			var obj = jQuery.parseJSON(jsonString);
				var errorMessages = new Array;
				errorMessages[0] = obj.error.msg;
				setErrorMessages(errorMessages);
				makeErrorMessagesVisible();
		});
	});
	
	/*
	* Get selected subscribers and check on validity on success send json-string to 
	*/
	$("#editSubscriber").click(function()  {
		deleteErrorMessage();
		$("#errorMessages").hide();
		var subscriber = new Array;
		subscriber[0] = 'edit';
		jQuery.merge(subscriber, getSelectedSubscribers());
		if (subscriber.length != 2)  {
			var errorMessages = new Array;
			errorMessages[0] = "Keinen oder mehr als einen Abonnenten ausgewählt. Bitte nur einen Abonnenten auswählen.";
			setErrorMessages(errorMessages);
			makeErrorMessagesVisible();	
		}
		else  {
			$("#subscriberData").attr("value", $.toJSON(subscriber));
			$("#subscriberListView").submit();
		}
	});
	
	/*
	* Flexigrid used on the subscriberListView
	*/
	$(function() {
        $("#subscriberListViewInternals").flexigrid({
				dataType: 'json',
                colModel : [
                        {display: 'ID', name : 'id', width: 60, sortable : true, align: 'left', hide: true},
                        {display: 'Datum', name : 'date', width: 150, sortable : true, align: 'left'},
                        {display: 'Geändert', name : 'changed', width: 150, sortable : true, align: 'left'},
                        {display: 'Empfänger', name : 'receiver', width: 100, sortable : true, align: 'left', hide: 'true'},
						{display: 'E-Mail', name : 'mail', width: 350, sortable : true, align: 'left'}
                ],
                sortname: "id",
                sortorder: "asc",
				title: 'Interne Abonnenten (0)',
				showTableToggleBtn: true
        });
		
		$("#subscriberListViewExternals").flexigrid({
				dataType: 'json',
                colModel : [
                        {display: 'ID', name : 'id', width: 60, sortable : true, align: 'left', hide: true},
                        {display: 'Datum', name : 'date', width: 150, sortable : true, align: 'left'},
                        {display: 'Geändert', name : 'changed', width: 150, sortable : true, align: 'left'},
                        {display: 'Empfänger', name : 'receiver', width: 100, sortable : true, align: 'left', hide: 'true'},
						{display: 'E-Mail', name : 'mail', width: 350, sortable : true, align: 'left'}
                ],
                sortname: "id",
                sortorder: "asc",
				title: 'Externe Abonnenten (0)',
				showTableToggleBtn: true
        });
		
		var subscriberData = new Array;
		
		subscriberData.push(getFunctionObject('subscriberListView'));
		
		var jsonString;
		$.post("http://admin.k6.de/index.php?id=22", subscriberData, function(data) {

			jsonString = $("." + data + ".tx-ttadminpanelservice-pi1").text().trim();
			$("#subscriberListViewInternals").flexAddData(jQuery.parseJSON(jsonString).Intern);
			$("#subscriberListViewExternals").flexAddData(jQuery.parseJSON(jsonString).Extern);
		});

	});
	
	/*
	*	Counter Update of SubscriberListView
	*/
	
	$("#subscriberListViewInternals").click(function (data)  {
		updateSelectedSubscribersCount($(this));
	});
	
	$("#subscriberListViewExternals").click(function (data)  {
		updateSelectedSubscribersCount($(this));
	});
 
});

/*
*	Highlight current menu point
*/

function setCurrentMenu()  {
	var url = document.URL;
	var queryString = url.split(".de/")[1];

	var mainMenuControl = document.getElementById('mainMenuFrame');
	var liElements = mainMenuControl.getElementsByTagName('li');
	var liElement;
	var aElement;
	for (i = 0; i < liElements.length; i++)  {
		liElement = liElements.item(i);	
		
		aElement = liElement.firstChild;
		
		if (document.URL == aElement.href)  {
			liElement.setAttribute('id', 'menubar_elements_cur');
		}
	}
	
}

/*
*	Check if Javascript is Active an hide the error Message
*/

function javascriptActive ()  {
	deleteErrorMessage();
	$("#errorMessages").hide();
	
	//Display the menubarelements remove display: none
	
	document.getElementById('mainMenuControlInvisible').setAttribute('id', 'mainMenuControl');
	document.getElementById('mainMenuInvisible').setAttribute('id', 'mainMenu'); 
}

function getFunctionObject (currentFunction)  {
	var functionName = new Object;
	functionName.name = "function";
	functionName.value = currentFunction; 
	return functionName;
}

function setErrorMessages (errorMessages)  {
	var errorMessageArea = document.getElementById('errorMessages');
	
	var table = document.createElement('table');
	table.appendChild(document.createElement('tbody'));

	for (i = 0; i < errorMessages.length; i++)  {

		var tr = document.createElement('tr');
		var td = document.createElement('td');
		
		var tdContent = document.createTextNode(errorMessages[i]);
		td.appendChild(tdContent);
		tr.appendChild(td);
		table.tBodies[0].appendChild(tr);			
	}
	
	errorMessageArea.appendChild(table);
}

function makeErrorMessagesVisible ()  {
	$("#errorMessages").fadeIn('slow');
}

function deleteErrorMessage ()  {
	$("#errorMessages").html('');
}

function getSelectedSubscribers ()  {
	var columns = ["uid", "date", "changed", "receiver", "mail"];
	var selectedSubscribers = $(".trSelected");
	var subscribers = new Array;
	for (var i = 0; i < selectedSubscribers.length; i++)  {
		var subscriberData = selectedSubscribers[i].childNodes;
		
		var subscriberObject = new Object();
		subscriberObject.uid = subscriberData[0].textContent;
		subscriberObject.date = subscriberData[1].textContent;
		subscriberObject.changed = subscriberData[2].textContent;
		subscriberObject.receiver = subscriberData[3].textContent;
		subscriberObject.mail = subscriberData[4].textContent;
		
		subscribers[i] = subscriberObject;

	}
	
	return subscribers;
}

function updateSelectedSubscribersCount (element) {
	var title = element.parent().siblings(".mDiv").children(".ftitle").text();
	element.parent().siblings(".mDiv").children(".ftitle").text(title.replace(/\d+/, element.children().children(".trSelected").length));	
}